<?php

namespace app\admin\controller\post;

use app\common\controller\Backend;

class Post extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->PostModel = model("Post.Post");
        $this->CategoryModel = model("Post.Category");
        $this->CollectModel = model("Post.Collect");
        $this->CommentModel = model("Post.Comment");
        $this->BusinessModel = model("Business.Business");
        $catelist=$this->CategoryModel->column('name','id');
        $statuslist = [
            '0' => '未采纳',
            '1' => '已采纳',
        ];
        $this->assign([
            'catelist' => $catelist,
            'statusList'=>$statuslist,
        ]);
        
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->PostModel
                ->with(['business', 'category','accepted'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->PostModel
                ->with(['business', 'category','accepted'])
                ->where($where)
                ->order($sort,  $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo $this->OrderModel->getlastSql();
            // exit;
            // halt(collection($list)->toArray());
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
  
    public function business()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->BusinessModel
                ->with(['source'])
                ->where($where)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->BusinessModel
                ->with(['source'])
                ->where($where)
                ->order($sort,  'asc')
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo $this->OrderModel->getlastSql();
            // exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) 
        {
            $params=$this->request->param('row/a');
            $business=$this->BusinessModel->find($params['busid']);
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
        
            // 发布帖子
            // 帖子表插入数据
            // 用户表更新余额
            // 消费记录表 插入
            // 加载模型
            $PostModel=model('Post.Post');
            $BusinessModel=model('Business.Business');
            $RecordModel=model('Business.Record');
            // 开启事务
            $PostModel->startTrans();
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            // 帖子表数据
            $PostData=[
                'title' => $params['title'],
                'content' => $params['content'],
                'point' => $params['point'],
                'busid' => $params['busid'],
                'cateid' => $params['cateid'],
                'status' => $params['status'],
            ];
            if(!empty($params['accept']))
            {
                $PostData['accept']=$params['accept'];
            }
            $PostStatus=$PostModel->validate('common/Post/Post')->save($PostData);
            if($PostStatus===FALSE)
            {
                $this->error($PostModel->getError());
                exit;
            }

            $money=$business['money'];
            // 用余额减去积分
            $update=bcsub($money,$params['point']);
            if($update<0)
            {
                $this->error("积分余额不足");
                exit;
            }
            // 客户表更新数据
            $BusinessData=[
                'id'=>$params['busid'],
                'money'=>$update,
            ];
            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];
            $BusinessStatus=$BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);
            if($BusinessStatus===FALSE)
            {
                $PostModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            if(!empty($params['accept']))
            {
                $accept=$this->BusinessModel->find($params['accept']);
                if(!$accept)
                {
                    $this->error('用户不存在');
                    exit;
                }
                $AcceptMoney=$accept['money'];
                $updateMoney=bcadd($AcceptMoney,$params['point']);
                // 客户表更新数据
                $AcceptData=[
                    'id'=>$params['accept'],
                    'money'=>$updateMoney,
                ];

                $AcceptStatus=$BusinessModel->validate(...$validate)->isUpdate(true)->save($AcceptData);
                if($AcceptStatus===FALSE)
                {
                    $PostModel->rollback();
                    $this->error($BusinessModel->getError());
                    exit;
                }
            }

            // 消费记录表插入数据
            $point=$params['point'];
            $content = "在知识问答社区发帖花费 ￥$point 元";
            $RecordData = [
                'total' => "-$point",
                'busid' => $params['busid'],
                'content' => $content
            ];

            $RecordStatus=$RecordModel->validate('common/Business/Record')->save($RecordData);
            if($RecordStatus===FALSE)
            {
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }
            if($PostStatus===FALSE || $BusinessStatus===FALSE || $RecordStatus===FALSE)
            {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error("添加帖子失败");
                exit;
            }else
            {
                $PostModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $this->success();
                exit;
            }
        }
        return $this->view->fetch();
    }
    public function edit($ids = null)
    {
        $row = $this->PostModel->with(['business','accepted'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        $this->assign("row", $row);
        if ($this->request->isAjax())
        {
            $params=$this->request->param('row/a');

            if(empty($params['accept_text']))
            {
                $params['accept']=null;
                
            }
            // halt($params);
            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];
            $AcceptData=[];
            // 更改采纳人
            if($row['accept'] && !empty($params['accept']) && $params['accept']!=$row['accept'])
            {
                $newaccept=$this->BusinessModel->find($params['accept']);
                if(!$newaccept)
                {
                    $this->error('用户不存在');
                    exit;
                }
                $oldaccept=$this->BusinessModel->find($row['accept']);
                if(!$oldaccept)
                {
                    $this->error('用户不存在');
                    exit;
                }
                $oldMoney=$oldaccept['money'];
                $newMoney=$newaccept['money'];
                $oldUpdate=bcsub($oldMoney,$params['point']);
                $newUpdate=bcadd($newMoney,$params['point']);
                // 客户表更新数据
                $OldAcceptData=[
                    'id'=>$row['accept'],
                    'money'=>$oldUpdate,
                ];
                $AcceptData=[
                    'id'=>$params['accept'],
                    'money'=>$newUpdate,
                ];
                $OldAcceptStatus=$this->BusinessModel->validate(...$validate)->isUpdate(true)->save($OldAcceptData);

                if($OldAcceptStatus===FALSE)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }
            }
            
            // 一开始没有被采纳人
            if(!$row['accept'] && !empty($params['accept']))
            {
                $accept=$this->BusinessModel->find($params['accept']);
                if(!$accept)
                {
                    $this->error('用户不存在');
                    exit;
                }
                $AcceptMoney=$accept['money'];
                $updateMoney=bcadd($AcceptMoney,$params['point']);
                // 客户表更新数据
                $AcceptData=[
                    'id'=>$params['accept'],
                    'money'=>$updateMoney,
                ];
            }

            // 把采纳状态设为未采纳
            if(empty($params['accept']) && $row['accept'])
            {
                $accept=$this->BusinessModel->find($row['accept']);
                if(!$accept)
                {
                    $this->error('用户不存在');
                    exit;
                }
                $AcceptMoney=$accept['money'];
                $updateMoney=bcsub($AcceptMoney,$params['point']);
                // 客户表更新数据
                $AcceptData=[
                    'id'=>$row['accept'],
                    'money'=>$updateMoney,
                ];
            }
            // 更新客户表余额
            $AcceptStatus=$this->BusinessModel->validate(...$validate)->isUpdate(true)->save($AcceptData);

            if($AcceptStatus===FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }
            
            // 更新帖子表
            $params['id']=$ids;
            $result=$this->PostModel->validate('common/Post/Post')->isUpdate(true)->save($params);
            if($result===false)
            {
                $this->error($this->PostModel->getError());
                exit;
            }
            $this->success();
            exit;
            
        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->PostModel->column('id');
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error('帖子不存在');
                exit;
            }
        }
        $result = $this->PostModel->destroy($ids);
        if ($result === FALSE) {
            $this->error($this->PostModel->getError());
            exit;
        } 
        $this->success();
        exit;
    }

    public function recycle()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->PostModel
                ->onlyTrashed()
                ->with(['business', 'category','accepted'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->PostModel
                ->onlyTrashed()
                ->with(['business', 'category','accepted'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function restore($ids = null)
    {
        $ids = empty($ids) ? [] : explode(',', $ids);
        $data = [];
        foreach ($ids as $item) {
            $res = $this->PostModel->onlyTrashed()->find($item);
            if (!$res) {
                $this->error('帖子不存在');
                exit;
            }
            $list = ['id' => $item, 'deletetime' => null];
            array_push($data, $list);
        }
        $result = $this->PostModel->isUpdate(true)->saveAll($data);
        if ($result===FALSE) {
            $this->error($this->PostModel->getError());
            exit;
        } 
        $this->success('还原帖子成功');
        exit;
    }

    /**
     * 真正删除帖子
     * 删除帖子表
     * 删除帖子收藏表
     * 删除帖子评论表
     */
    public function destroy($ids = null)
    {
        $ids = empty($ids) ? [] : explode(',', $ids);

        $row = $this->PostModel->onlyTrashed()->column('id');
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error('帖子不存在');
                exit;
            }
            $where=[
                'postid'=>$item
            ];
            $collect=$this->CollectModel->where($where)->column('id');
            $comment=$this->CommentModel->where($where)->column('id');
            
        }
        // halt($collect);

        $PostStatus=$this->PostModel->destroy($ids,true);
        if($PostStatus===FALSE)
        {
            $this->error($this->PostModel->getError());
            exit;
        }

        // 删除成功 删除一些关联内容
        $CollectStatus=$this->CollectModel->destroy($collect);
        if($CollectStatus===FALSE)
        {
            $this->error($this->CollectModel->getError());
            exit;
        }

        $CommentStatus=$this->CommentModel->destroy($comment);
        
        if($CommentStatus===FALSE)
        {
            $this->error($this->CommentModel->getError());
            exit;
        }
        
        $this->success('删除成功');
        exit;
        

    }
}